
import uuid
from typing import Type, Generic, Any, List
from sqlalchemy import delete, desc, update
from sqlalchemy.ext.asyncio import AsyncSession
from model.entitys import Base

async def insert_pojo(session: AsyncSession, Pojo: Type[Base], obj_dict: dict):
    session.add(Pojo(**obj_dict))

async def find_pojos(session: AsyncSession, Pojo: Type[Base], query, obj):
    pojo_list = (await session.execute(query.order_by(desc(Pojo.created_at)).offset(
        (obj.page_no - 1) * obj.page_size).limit(obj.page_size))).scalars().all()

    return pojo_list

async def update_pojo(session: AsyncSession, Pojo: Type[Base], obj_dict: dict):
    await session.execute(update(Pojo).where(Pojo.id == obj_dict["id"]), obj_dict)

async def delete_pojo(session: AsyncSession, Pojo: Type[Base], id: str):
    await session.execute(delete(Pojo).where(Pojo.id == id))

async def insert_pojo_by_many(session: AsyncSession, id_list: List[str], obj_dict1: dict, Pojo2: Type[Base], field2: str, field3: str):
    obj_dict2_list = []
    for id in id_list:
        # # 方式一:
        # obj_dict2 = {
        #     "id": uuid.uuid1().__str__(),
        #     field2: obj_dict1["id"],
        #     field3: id,
        #     "remarks": obj_dict1["remarks"]
        # }
        # obj_dict2_list.append(Pojo2(**obj_dict2))

        # 方式二:
        p2 = Pojo2()
        p2.id = uuid.uuid1().__str__()
        setattr(p2, field2, obj_dict1["id"])
        setattr(p2, field3, id)
        p2.remarks = obj_dict1["remarks"]
        obj_dict2_list.append(p2)

    session.add_all(obj_dict2_list)

async def insert_pojo_by_relation(session: AsyncSession, Pojo1: Type[Base], obj_dict1: dict, field1: str, Pojo2: Type[Base], field2: str, field3: str):
    id_list = obj_dict1[field1]
    obj_dict1.pop(field1)

    session.add(Pojo1(**obj_dict1))

    await insert_pojo_by_many(session, id_list, obj_dict1, Pojo2, field2, field3)

async def delete_pojo_by_relation(session: AsyncSession, Pojo1: Type[Base], id: str, Pojo2: Type[Base], field: str):
    await session.execute(delete(Pojo2).where(getattr(Pojo2, field) == id))

    await session.execute(delete(Pojo1).where(Pojo1.id == id))

async def update_pojo_by_relation(session: AsyncSession, Pojo1: Type[Base], obj_dict1: dict, field1: str, Pojo2: Type[Base], field2: str, field3: str):
    await session.execute(delete(Pojo2).where(getattr(Pojo2, field2) == obj_dict1["id"]))

    await insert_pojo_by_many(session, obj_dict1[field1], obj_dict1, Pojo2, field2, field3)

    obj_dict1.pop(field1)
    await session.execute(update(Pojo1).where(Pojo1.id == obj_dict1["id"]), obj_dict1)













































































































































